<template>
  <div>
    <el-tag :key="index"
            v-for="(tag,index) in dynamicTags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
      {{tag}}
    </el-tag>
    <el-input class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm">
    </el-input>
    <el-button v-else
               class="button-new-tag"
               size="small"
               @click="showInput">+ New Tag</el-button>
  </div>
</template>

<script>
import { editparams } from '@/api/Param.js'
export default {
  data () {
    return {
      inputVisible: false,
      inputValue: ''
    }
  },
  props: {
    dynamicTags: {
      type: [Array, String],
      require: true
    },
    id: {
      type: Number,
      require: true
    },
    attrId: {
      type: Number,
      require: true
    },
    attr_sel: {
      type: String,
      require: true
    },
    attr_name: {
      type: String,
      require: true
    }
  },
  created () {

  },

  methods: {
    // tag
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async handleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
      // 更新数据
      const val = this.dynamicTags.join(' ')
      console.log(val)
      await editparams(this.attrId, this.id, {
        attr_name: this.attr_name,
        attr_sel: this.attr_sel,
        attr_vals: val
      })
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
